import ReduxThunk from "redux-thunk";
// import thunkMiddleware from "redux-thunk";

import { createLogger } from "redux-logger";
import { createStore, applyMiddleware } from "redux";
import createSagaMiddleware from "redux-saga";
import { createWrapper } from "next-redux-wrapper";

import combineReducers from "./reducers";
import rootSaga from "./sagas";

const bindMiddleware = (middleware) => {
  if (process.env.NODE_ENV !== "production") {
    const { composeWithDevTools } = require("redux-devtools-extension");
    return composeWithDevTools(applyMiddleware(...middleware));
  }
  return applyMiddleware(...middleware);
};

const makeConfiguredStore = (reducer, initialState = {}) => {
  // 1: Create the middleware
  const sagaMiddleware = createSagaMiddleware();
  // logger middleware
  const logger = createLogger();

  // 2: Add an extra parameter for applying middleware:
  const store = createStore(
    reducer,
    initialState,
    bindMiddleware([sagaMiddleware, ReduxThunk, logger])
  );
  // 3: Run your sagas on server
  store.sagaTask = sagaMiddleware.run(rootSaga);
  // 4: now return the store:
  return store;
};

const makeStore = (initialState) => {
  const isServer = typeof window === "undefined";

  if (isServer) {
    // if it's on server side, create a store
    const store = makeConfiguredStore(combineReducers, initialState);
    // console.log("服务端渲染 store====>", store, isServer);
    return store;
  } else {
    // we need it only on client side, create a store which will persist
    const { persistStore, persistReducer } = require("redux-persist");
    const storage = require("redux-persist/lib/storage").default;

    const persistConfig = {
      key: "nextjs",
      whitelist: ["counter"], // only counter will be persisted, add other reducers if needed
      storage, // if needed, use a safer storage
    };

    const persistedReducer = persistReducer(persistConfig, combineReducers);
    const store = makeConfiguredStore(persistedReducer);

    store.__persistor = persistStore(store); // This creates a persistor object & push that persisted object to .__persistor, so that we can avail the persistability feature
    console.log("客户端渲染 store====>", store, isServer);
    return store;
  }
};

// Export the wrapper & wrap the pages/_app.js with this wrapper only
export const wrapper = createWrapper(makeStore, { debug: false });
